<template>
	<view>
		<zmm-watermark :watermark="userStore.watermark" v-if="userStore.watermark"></zmm-watermark>
		<!--导航栏-->
		<pageLayout
			:barTitle="title"
			:isSearchNull="isSearchNull"
			:isOpen="isOpen"
			@rightClick="clickSearch">
		</pageLayout>
		<!--查询弹窗-->
		<up-popup :z-index="90" :show="isOpen" @close="closeSearch" mode="top">
			<view @touchmove.stop.prevent>
			<scroll-view class="search" scroll-y="true" @touchmove.stop>
				<view class="search-form">
					<uni-forms ref="searchRef" :modelValue="searchModel" label-width="160rpx">
						<uni-forms-item label="采购单号">
							<uni-easyinput v-model="searchModel.number" placeholder="请输入采购单号" />
						</uni-forms-item>
						<uni-forms-item label="仓库名称">
							<uni-easyinput v-model="searchModel.warehouseName" placeholder="请输入仓库名称" />
						</uni-forms-item>
						<uni-forms-item label="采购人员">
							<uni-easyinput v-model="searchModel.purchaseUserName" placeholder="请输入采购人员" />
						</uni-forms-item>
						<uni-forms-item label="供应商">
							<uni-easyinput v-model="searchModel.supplierName" placeholder="请输入供应商" />
						</uni-forms-item>
						<uni-forms-item label="采购状态">
							<uni-data-select
								v-model="searchModel.status"
								placeholder="请选择采购状态"
								:localdata="allStatusList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="商品名称">
							<uni-easyinput v-model="searchModel.products" placeholder="请输入商品名称" />
						</uni-forms-item>
						<uni-forms-item label="开始时间">
							<uni-datetime-picker type="datetime" placeholder="请选择开始时间" v-model="searchModel.startTime"/>
						</uni-forms-item>
						<uni-forms-item label="结束时间">
							<uni-datetime-picker type="datetime" placeholder="请选择结束时间" v-model="searchModel.endTime"/>
						</uni-forms-item>
					</uni-forms>
					<view class="search-footer main-flex">
						<up-button
							class="search-footer-item"
							text="搜索"
							type="primary"
							@click="searchSubmit"
							icon="search"></up-button>
						<up-button
							class="search-footer-item"
							@click="resetSubmit"
							text="重置"></up-button>
					</view>
				</view>
			</scroll-view>
			</view>
		</up-popup>
		<view class="content">
			<!--操作-->
			<view class="operate main-flex">
				<view class="operate-item" v-if="checkPermi(['zhouyz:purchaseOrder:add'])">
					<up-button
						class="operate-btn main-flex"
						size="mini"
						type="primary"
						@click="addFun">
						<uni-icons class="operate-btn-icon" type="plusempty" size="28rpx" color="#ffffff"></uni-icons>
						<view class="operate-btn-text">新增采购单</view>
					</up-button>
				</view>
			</view>
			<!--内容-->
			<view class="table">
				<ty-table
					:data="tableList"
					:columns="columns"
					:sortable="true"
					@row-click="rowClick"
					:cellClassName="() => 'table-cell'"
					:headerCellClassName="() => 'table-cell'"
					:rowClassName="() => 'table-row'"
					:isOperateBtn="(row) => {
						return (checkPermi(['zhouyz:purchaseOrder:edit']) && row.status === 0)
						|| (checkPermi(['zhouyz:purchaseOrder:confirm']) && row.status === 1)
						|| (checkPermi(['zhouyz:purchaseOrder:send']) && row.status === 2)
						|| (checkPermi(['zhouyz:purchaseOrder:received']) && row.status === 4)
						|| (checkPermi(['zhouyz:purchaseOrder:join']) && row.status === 5)
						|| (checkPermi(['zhouyz:purchaseOrder:financeAudit']) && row.status === 7)
						|| (checkPermi(['zhouyz:purchaseOrder:invalid']) && row.status < 3)
						// || (checkPermi(['zhouyz:purchaseOrder:remove']) &&  row.status === 3)
					}"
					stripe
					border>
					<template v-slot:order="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								采购单：
								<text class="table-td-text">{{row.number}}</text></view>
							<view class="table-td-row">
								需求单：
								<text class="table-td-text">{{row.demandNumber}}</text></view>
							<view class="table-td-row">
								制单人员：
								<text class="table-td-text">{{row.createUserName}}</text></view>
							<view class="table-td-row">
								仓库名称：
								<text class="table-td-text">{{row.warehouseName}}</text></view>
							<view class="table-td-row">
								采购人员：
								<text class="table-td-text">{{row.purchaseUserName}}</text></view>
							<view class="table-td-row">
								供应商：
								<text class="table-td-text">{{row.supplierName}}</text></view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
								采购金额：
								<text class="table-td-text">{{row.allPrice}}</text></view>
						</view>
					</template>
					<template v-slot:pay="{ row }">
						<view class="table-td-cell">
							<view class="table-td-row">
								下单时间：
								<text class="table-td-text">{{row.createTime}}</text></view>
							<view class="table-td-row">
								入库时间：
								<text class="table-td-text">{{row.storageInCreateTime}}</text></view>
							<view class="table-td-row main-flex">
								采购状态：
								<uni-tag type="success" :class="`purchase-status-${row.status}`" size="small" :text="arrText(allStatusList, row.status)" /></view>
							<view class="table-td-row">
								采购说明：
								<text class="table-td-text">{{row.remark}}</text></view>
							<view class="table-td-row">
								付款时间：
								<text class="table-td-text">{{row.payTime}}</text></view>
							<view class="table-td-row" v-if="checkPermi(['zhouyz:purchaseOrder:price'])">
								付款金额：
								<text class="table-td-text">{{row.payPrice}}</text></view>
							<view class="table-td-row">
								付款说明：
								<text class="table-td-text">{{row.payRemark}}</text></view>
						</view>
					</template>
					<template v-slot:operate="{ row }">
						<view class="table-td-operate table-cell table-td-row main-flex">
							
							<view v-if="checkPermi(['zhouyz:purchaseOrder:edit']) && row.status === 0" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="launchOne(row.id)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">发起审核</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:purchaseOrder:edit']) && row.status === 0" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="editFun(row.id)">
									<uni-icons class="table-operate-btn-icon" type="compose" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">修改</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:purchaseOrder:confirm']) && row.status === 1" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="confirmOne(row.id)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">审核通过</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:purchaseOrder:send']) && row.status === 2" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="sendOne(row)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">确认发货</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:purchaseOrder:received']) && row.status === 4" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="received(row.id)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">确认收货</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:purchaseOrder:join']) && row.status === 5" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="join(row.id)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">采购单入库</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:purchaseOrder:financeAudit']) && row.status === 7" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="primary"
									@click.stop="financeAudit(row)">
									<uni-icons class="table-operate-btn-icon" type="auth" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">财务审核</view>
								</up-button>
							</view>
							<view v-if="checkPermi(['zhouyz:purchaseOrder:invalid']) && row.status < 3" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="error"
									@click.stop="invalid(row)">
									<uni-icons class="table-operate-btn-icon" type="trash" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">采购单作废</view>
								</up-button>
							</view>
							<!-- <view v-if="checkPermi(['zhouyz:purchaseOrder:remove']) &&  row.status === 3" class="table-operate-btn main-flex">
								<up-button
									size="mini"
									type="error"
									@click.stop="remove(row.id)">
									<uni-icons class="table-operate-btn-icon" type="trash" size="24rpx" color="#ffffff"></uni-icons>
									<view class="table-operate-btn-text">删除</view>
								</up-button>
							</view> -->
						</view>
					</template>
					<template v-slot:empty>
						<view class="table-empty">
							<up-empty mode="data"/>
						</view>
					</template>
				</ty-table>
			</view>
			<!--分页-->
			<view class="pagination" v-show="total > 0">
				<ty-pagination
					:total="total"
					:pageSize="pageSize"
					:currentPage="pageNum"
					:pageSizes="[10, 20, 30, 50]"
					mode="simple"
					layout="first,prev,page,next,last"
					@sizeChange="sizeChange"
					@change="pageChange">
				</ty-pagination>
			</view>
		</view>
		
		<!--确认弹窗-->
		<up-popup :z-index="90" round="5" closeable :show="showEdit" @close="editCancel" mode="center">
			<view class="edit">
				<view class="edit-header">采购单作废</view>
				<view class="edit-form">
					<uni-forms
						ref="editRef"
						:modelValue="editModel"
						label-width="160rpx">
						<uni-forms-item label="ID" name="id" style="display: none;">
							<view class="edit-form-checkbox main-flex">
								<uni-easyinput v-model="editModel.id" />
							</view>
						</uni-forms-item>
						<uni-forms-item label="备注" name="remark">
							<uni-easyinput type="textarea" v-model="editModel.remark" placeholder="请输入备注"></uni-easyinput>
						</uni-forms-item>
					</uni-forms>
					<view class="edit-footer main-flex">
						<up-button
							class="edit-footer-item"
							@click="editCancel"
							text="取消"></up-button>
						<up-button
							class="edit-footer-item"
							text="确认"
							type="primary"
							@click="editConfirm"></up-button>
					</view>
				</view>
			</view>
		</up-popup>
		
	</view>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app';
import { computed, onMounted, ref, getCurrentInstance } from 'vue'
import { tab, auth, modal } from "@/plugins"
import { getTitle } from "@/utils/getter"
import { checkPermi, checkRole, checkOnlyPermi, checkOnlyRole } from "@/utils/permission"
import { purchaseOrderStatus } from "@/api/system/dict/data"
import { 
	purchaseOrder,
	sureReceiving,
	launchExamineOrder,
	examineOrder,
	sureJoinWarehouse,
	delPurchaseOrder,
	purchaseInvalid } from "@/api/erp_api/purchase"
import { isObjectEmptySimple, copyText, arrText, getRecentDays } from '@/utils/ty.js'
import useUserStore from '@/store/modules/user'

	const userStore = useUserStore()
	const { proxy } = getCurrentInstance()
	// 标题设置
	const title = ref('')
	onLoad((option) => {
		title.value = getTitle(userStore.menu)
		uni.setNavigationBarTitle({
			title: title.value 
		})
		uni.$on('refreshList', () => {
			getList()
		})
	})
	
	
	// 新增采购单
	const addFun = () => {
		uni.navigateTo({
			url: '/pages/purchase/purchaseOrderAdd'
		})
	}
	
	// 采购状态
	const allStatusList = ref([])
	const getPurchaseOrderStatus = () => {
		return purchaseOrderStatus().then(res => {
			allStatusList.value = res.data.map(item => {
				return {
					...item,
					value: item.dictValue,
					text: item.dictValue == 3 ? '审核不通过/作废' : item.dictLabel
				}
			}) || []
		})
	}
	
	// 搜索相关
	const isSearchNull = ref(true)
	const isOpen =  ref(false)
	const clickSearch = (val) => {
		isOpen.value = val
	}
	const closeSearch = (val) => {
		isOpen.value = false
	}
	// 确认搜索
	const searchRef = ref(null)
	const searchModel = ref({
		number: '',
		purchaseUserName: '',
		warehouseName: '',
		supplierName: '',
		status: '',
		startTime: getRecentDays(15),
		endTime: '',
		products: ''
	})
	const searchSubmit = () => {
		pageNum.value = 1
		tableList.value = []
		isOpen.value = false
		searchFirst()
	}
	// 重置搜索
	const resetSubmit = () => {
		// searchRef.value.resetFields()
		searchModel.value = {
			number: '',
			purchaseUserName: '',
			warehouseName: '',
			supplierName: '',
			status: '',
			startTime: getRecentDays(15),
			endTime: '',
			products: ''
		}
		isSearchNull.value = true
		isOpen.value = false
		searchFirst()
	}
	
	
	// 数据查询
	const pageNum = ref(1)
	const pageSize = ref(10)
	const total = ref(0)
	const tableList = ref([])
	const isLoading = ref(false)
	
	// 表格头部
	const columns = ref([
		{ title: '采购信息', key: 'order' },
		{ title: '付款入库', key: 'pay' }
	])
	
	// 从第一页查询
	const searchFirst = () => {
		pageNum.value = 1
		tableList.value = []
		isSearchNull.value = isObjectEmptySimple(searchModel.value)
		getList()
	}
	//页数切换
	const pageChange = (page) => {
		pageNum.value = page
		getList()
	}
	//每页条数切换
	const sizeChange = (size) => {
		pageSize.value = size
		getList()
	}
	
	const getList = () => {
		const params = {
			pageNum: pageNum.value,
			pageSize: pageSize.value
		}
		if (searchModel.value.number) {
			params.number = searchModel.value.number
		}
		if (searchModel.value.warehouseName) {
			params.warehouseName = searchModel.value.warehouseName
		}
		if (searchModel.value.purchaseUserName) {
			params.purchaseUserName = searchModel.value.purchaseUserName
		}
		if (searchModel.value.supplierName) {
			params.supplierName = searchModel.value.supplierName
		}
		if (searchModel.value.products) {
			params.products = searchModel.value.products
		}
		if (searchModel.value.status || searchModel.value.status === 0) {
			params.status = searchModel.value.status
		}
		if (searchModel.value.startTime) {
			params.startTime = searchModel.value.startTime
		}
		if (searchModel.value.endTime) {
			params.endTime = searchModel.value.endTime
		}
		isLoading.value = true
		uni.showLoading({
			title: '数据加载中...'
		})
		purchaseOrder(params).then(res => {
			tableList.value = res.rows || []
			total.value = res.total
			isLoading.value = false
			uni.hideLoading()
    }).catch(() => {
			isLoading.value = false
			uni.hideLoading()
		})
	}
	
	// 点击行
	const rowClick = (row) => {
		if (checkPermi(['zhouyz:purchaseOrderDetail:list'])) {
			uni.navigateTo({
				url: `/pages/purchase/purchaseOrderDetail?id=${row.id}`
			})
		}
	}
	
	// 确认收货
	const received = (id) => {
		uni.showModal({
			title: '确认收货',
			content: `请通知仓库清点商品数量，如出现收货数量不对，请在【入库】完成后发起【采购退货】！`,
			success: function (res) {
				if (res.confirm) {
					receivedOne(id)
				}
			}
		})
	}
	// 采购单入库
	const join = (id) => {
		uni.showModal({
			title: '采购单入库',
			content: `请点击【详情】确认入库数量，如出现收货数量不对，请在【入库】完成后发起【采购退货】！`,
			success: function (res) {
				if (res.confirm) {
					joinOne(id)
				}
			}
		})
	}
	
	// 采购审核
	const confirm = (id) => {
		uni.showModal({
			title: '采购审核',
			content: `请确认审核通过？`,
			success: function (res) {
				if (res.confirm) {
					confirmOne(id)
				}
			}
		})
	}
	
	// 删除
	const remove = (id) => {
		uni.showModal({
			title: '采购单删除',
			content: `请确认删除该采购单？`,
			success: function (res) {
				if (res.confirm) {
					removeOne(id)
				}
			}
		})
	}
	
	const isSubmit = ref(false)
	
	
	// 发起审核
	const launchOne = (id) => {
		if (isSubmit.value) return false
		isSubmit.value = true
		launchExamineOrder({
			orderId: id
		}).then(res => {
			modal.showToast('发起成功')
			getList()
			isSubmit.value = false
		}).catch((err) => {
			modal.showToast(err)
			isSubmit.value = false
		})
	}
	// 审核
	const confirmOne = (id) => {
		if (isSubmit.value) return false
		isSubmit.value = true
		examineOrder({
			orderId: id
		}).then(res => {
			modal.showToast('审核通过')
			getList()
			isSubmit.value = false
		}).catch((err) => {
			modal.showToast(err)
			isSubmit.value = false
		})
	}
	
	// 发货
	const sendOne = (row) => {
		uni.navigateTo({
			url: `/pages/purchase/purchaseOrderSend?id=${row.id}`
		})
	}
	// 修改
	const editFun = (id) => {
		uni.navigateTo({
			url: `/pages/purchase/purchaseOrderEdit?id=${id}`
		})
	}
	// 收货
	const receivedOne = (id) => {
		if (isSubmit.value) return false
		isSubmit.value = true
		sureReceiving({
			orderId: id
		}).then(res => {
			modal.showToast('收货完成')
			getList()
			isSubmit.value = false
		}).catch((err) => {
			modal.showToast(err)
			isSubmit.value = false
		})
	}
	// 入库
	const joinOne = (id) => {
		if (isSubmit.value) return false
		isSubmit.value = true
		sureJoinWarehouse({
			orderId: id
		}).then(res => {
			modal.showToast('入库完成')
			getList()
			isSubmit.value = false
		}).catch((err) => {
			modal.showToast(err)
			isSubmit.value = false
		})
	}
	// 删除
	const removeOne = (id) => {
		if (isSubmit.value) return false
		isSubmit.value = true
		delPurchaseOrder({
			orderId: id
		}).then(res => {
			modal.showToast('删除完成')
			getList()
			isSubmit.value = false
		}).catch((err) => {
			modal.showToast(err)
			isSubmit.value = false
		})
	}
	
	// 财务审核
	const financeAudit = (row) => {
		uni.navigateTo({
			url: `/pages/purchase/purchaseOrderDetail?id=${row.id}`
		})
	}
	
	// 作废
	const editModel = ref({
		id: '',
		remark: ''
	})
	const showEdit = ref(false)
	
	//打开作废
	const editObj = ref({})
	const invalid = (row) => {
		showEdit.value = true
		editModel.value.id = row.id
		editModel.value.remark = ''
		editObj.value = {...row}
	}
	
	// 取消作废
	const editCancel = () => {
		showEdit.value = false
		editModel.value = {
			id: '',
			remark: ''
		}
	}
	
	// 确认作废
	const editConfirm = () => {
		if (isSubmit.value) return false
		isSubmit.value = true
		purchaseInvalid({
			...editObj.value,
			...editModel.value
		}).then(res => {
			editCancel()
			modal.showToast('采购单已作废')
			getList()
			isSubmit.value = false
		}).catch((err) => {
			modal.showToast(err)
			isSubmit.value = false
		})
	}
	
	onMounted(async () => {
		await getPurchaseOrderStatus()
		searchFirst()
	})
</script>

<style scoped lang="scss">
.goods {
	align-items: flex-start;
	&_r {
		padding-left: 20rpx;
	}
}
.table-td-long1 {
	max-width: 180rpx;
}
.table-td-long {
	max-width: 200rpx;
}
</style>
